package com.example.jmm.myndk;

import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.jmm.myndk.USBMonitor.OnDeviceConnectListener;

import java.io.File;
import java.util.Iterator;

public class MainActivity extends AppCompatActivity {

    private USBMonitor mUSBMonitor;
    private Button listbtn;
    private Button startbtn;
    private Button stopbtn;
    private TextView tv;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listbtn = (Button)findViewById(R.id.listbtn);
        startbtn = (Button)findViewById(R.id.startbtn);
        stopbtn = (Button)findViewById(R.id.stopbtn);

        tv = (TextView) findViewById(R.id.tv);
        mUSBMonitor = new USBMonitor(this, mOnDeviceConnectListener);

        listbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Iterator<UsbDevice> deviceIterator = mUSBMonitor.getDeviceList();
/*
                 while(deviceIterator.hasNext()){
                 UsbDevice device = deviceIterator.next();
                 String devname = device.getDeviceName();
                 //请求权限
                 if(device.getDeviceName() == "1d6b:0102") {
                     Log.i("MyNdk", "find the device!!");
                 mUSBMonitor.requestPermission(device);
                 }
                 }
*/

                 File device = new File("/dev/video0");
                 device.setReadable(true);
                 device.setWritable(true);
                 if (!device.canRead() || !device.canWrite()) {
                    try {
                        Log.i("MyNdk", "0000");
                        String cmd = "su & chmod 666 " + device.getAbsolutePath() + "\n" + "exit\n";
                        Log.i("MyNdk", "1111");
                        Process su = Runtime.getRuntime().exec(cmd);
                        Log.i("MyNdk", "2222");
                        /*
                        Log.i("MyNdk", "0000Command execute failed.");
                        Process su = Runtime.getRuntime().exec("su\n", null,null);
                        Log.i("MyNdk", "1111Command execute failed.");
                        OutputStream os = su.getOutputStream();
                        Log.i("MyNdk", "2222Command execute failed.");
                        os.write(("chown system:camera /dev/video0").getBytes("ASCII"));
                        Log.i("MyNdk", "3333Command execute failed.");
                        os.flush();
                        Log.i("MyNdk", "4444Command execute failed.");
                        os.close();
                        Log.i("MyNdk", "5555Command execute failed.");

                        su.waitFor();
                        Log.i("MyNdk", "6666Command execute failed.");
                        int existValue = su.exitValue();
                        Log.i("MyNdk", "7777Command execute failed.");
                        if(existValue != 0) {
                            Log.i("MyNdk", "Change file permission failed.");
 //                           throw new SecurityException();
                        }
                        */
                    } catch (Exception e) {
                        Log.i("MyNdk", "Command execute failed.====");
                        //throw new SecurityException();
                    }
                 }

                new TaskThread().start();

            }
        });

        startbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv.setText(new MyNdk().nativestart("/sdcard/sunny/recsunny.avi"));
            }
        });

        stopbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    tv.setText(new MyNdk().nativestop());
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mUSBMonitor != null) {
            mUSBMonitor.register();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    {
                        String str = msg.getData().getString("message");
                        tv.setText(str);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    class TaskThread extends Thread {
        public void run() {
            String str = new MyNdk().nativelist();
            Bundle data = new Bundle();
            data.putString("message",str);
            Message message = new Message();
            message.setData(data);
            message.what = 0;
            handler.sendMessage(message);
        }
    }

    private final OnDeviceConnectListener mOnDeviceConnectListener = new OnDeviceConnectListener() {
        @Override
        public void onAttach(final UsbDevice device) {
            Toast.makeText(MainActivity.this, "USB_DEVICE_ATTACHED", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onConnect(final UsbDevice device) {
            new TaskThread().start();
        }
    };
}
